package com.dingding.manager.modules.dirver.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.special.Specialuserlogin;
import com.dingding.manager.common.beans.driver.SpecialUserAuthInfo;
import com.dingding.manager.common.beans.driver.Specialuserinfo;
import com.dingding.manager.common.beans.driver.Specialuservehicleinfo;
import com.dingding.manager.common.dao.Db;
import com.dingding.manager.common.dao.Page;
import com.dingding.manager.common.exception.BussinessException;
import com.dingding.manager.common.exception.enums.BizExceptionEnum;
import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.util.DateUtil;
import com.dingding.manager.core.util.SqlUtil;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.dirver.dao.DriverManagerDao;
import com.dingding.manager.modules.dirver.dto.ReqAddDriverDTO;
import com.dingding.manager.modules.dirver.dto.ResDriverBasicInfoDTO;
import com.dingding.manager.modules.dirver.dto.RespDetailDriverDTO;
import com.dingding.manager.modules.dirver.dto.RespGetDriverDTO;
import com.dingding.manager.modules.dirver.sql.DriverSql;

/**
 * 
 * @Description: 司机管理相关业务Dao实现
 * @author haoxiaojun
 * @date 2016年12月3日 下午5:18:38
 * @since V 2.5.7
 */
@Component("driverManagerDao")
public class DrvierManagerDaoImpl implements DriverManagerDao {

	Logger log = Logger.getLogger(this.getClass());

	/**
	 * 
	 * @Description: 司机管理业务之司机资料编辑
	 * @author haoxiaojun
	 * @date 2016年12月3日 下午5:20:11
	 * @since V 2.5.7
	 */
	@Override
	public Boolean editDriver(ReqAddDriverDTO reqAddDriver) {

		if (ToolUtil.isEmpty(reqAddDriver)) {
			return false;
		}

		if (ToolUtil.isEmpty(reqAddDriver.getWorkLicenseImage())) {
			reqAddDriver.setWorkLicenseImage("");
		}
		if (ToolUtil.isEmpty(reqAddDriver.getWorkLicenseNumber())) {
			reqAddDriver.setWorkLicenseNumber("");
		}

		Date jszLssueDate = DateUtil.parseDate(reqAddDriver.getJszLssueDate());
		Date xszLssueDate = DateUtil.parseDate(reqAddDriver.getXszLssueDate());
		Date jszValidityPeriod = DateUtil.parseDate(reqAddDriver.getJszValidityPeriod());

		// 通过id查出所有需要进行修改的表
		Specialuservehicleinfo specialuservehicleinfo = Db.findById(reqAddDriver.getUvId(),
				Specialuservehicleinfo.class);
		Specialuserinfo specialuserinfo = Db.findById(reqAddDriver.getSuId(), Specialuserinfo.class);
		SpecialUserAuthInfo ddSpecialUserAuthInfo = Db.findById(reqAddDriver.getSpecialAuthInfoId(),
				SpecialUserAuthInfo.class);

		// 复制字段
		BeanUtils.copyProperties(reqAddDriver, specialuservehicleinfo);
		BeanUtils.copyProperties(reqAddDriver, specialuserinfo);
		BeanUtils.copyProperties(reqAddDriver, ddSpecialUserAuthInfo);

		specialuservehicleinfo.setXszLssueDate(xszLssueDate);
		ddSpecialUserAuthInfo.setJszValidityPeriod(jszValidityPeriod);
		ddSpecialUserAuthInfo.setJszLssueDate(jszLssueDate);

		// 更新到数据库
		Db.update(specialuservehicleinfo);
		Db.update(specialuserinfo);
		Db.update(ddSpecialUserAuthInfo);

		return true;
	}

	/**
	 * 
	 * @Description: 司机管理业务之修改司机状态
	 * @author haoxiaojun
	 * @return void
	 * @date 2016年12月3日 下午3:46:49
	 * @since V 2.5.7
	 * 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Boolean modifyDriver(String suId, Integer suvStatus) {

		if (ToolUtil.isEmpty(suId) || ToolUtil.isEmpty(suvStatus)) {
			return false;
		}

		SpecialUserAuthInfo sp = Db.findById(suId, SpecialUserAuthInfo.class);
		sp.setIsDel(suvStatus);
		Db.update(sp);

		return true;

	}

	/**
	 * 
	 * @Description: 司机管理业务之列表展示司机
	 * @author haoxiaojun
	 * @date 2016年12月3日 下午5:19:43
	 * @since V2.5.7
	 * 
	 */
	@Override
	@Transactional(readOnly = true)
	public Page<RespGetDriverDTO> getDriver(Integer start, Integer length, Integer cityId, Integer provice_id,
			Integer companyId, Integer suvStatus, String dvName, String submitTime) {

		StringBuffer driverListSql = new StringBuffer(DriverSql.DRIVER_LIST);
		Integer row = (int) Math.ceil((double) (start + 1) / length);
		Page<RespGetDriverDTO> page = new Page<>(row, length);
		// 初始化查询条件存放的object数组
		ArrayList<Object> parms = new ArrayList<Object>();
		// 获取用户有权限访问的机构集合
		List<Integer> organizationList = ShiroKit.getOrganizationIdList();
		if (!organizationList.isEmpty()) {
			parms.addAll(organizationList);
			driverListSql.append(" AND c.organizationId IN (" + SqlUtil.parse(organizationList) + ")");
			if (ToolUtil.isNotEmpty(cityId)) {
				driverListSql.append(" AND c.cityId = ? ");
				parms.add(cityId);
			}
			if (ToolUtil.isNotEmpty(provice_id)) {
				driverListSql.append(" AND g.provice_id = ? ");
				parms.add(provice_id);
			}

			if (ToolUtil.isNotEmpty(companyId)) {
				driverListSql.append(" AND c.organizationId = ? ");
				parms.add(companyId);
			}
			if (ToolUtil.isNotEmpty(suvStatus)) {
				if (suvStatus == 2) {
					driverListSql.append(" AND b.suvStatus = 2 ");
				}
				if (suvStatus == 1) {
					driverListSql.append(" AND b.suvStatus = 1 ");
				}
				if (suvStatus == 3) {
					driverListSql.append(" AND b.suvStatus = 3 ");
				}
				if (suvStatus == 0) {
					driverListSql.append(" AND b.suvStatus <> 2 ");
				}
			}
			if (ToolUtil.isNotEmpty(dvName)) {
				driverListSql.append(" AND ( c.trueName like '%" + dvName + "%' OR b.lisencePlate like '%" + dvName
						+ "%' OR a.telPhone like '%" + dvName + "%' OR c.idCard like '%" + dvName + "%')");
			}
			if (ToolUtil.isNotEmpty(submitTime)) {
				driverListSql.append(" AND b.submitTime like '%" + submitTime + "%'");
			}
			driverListSql.append(" ORDER BY b.submitTime DESC ");

			String sql = driverListSql.toString();

			page = Db.querySqlByPage(RespGetDriverDTO.class, page, sql, parms.toArray());
		}

		return page;

	}

	/**
	 * 
	 * @Description: 司机管理业务之司机详情
	 * @author haoxiaojun
	 * @date 2016年12月3日 下午5:20:23
	 * @since V 2.5.7
	 */
	@Override
	@Transactional(readOnly = true)
	public RespDetailDriverDTO detailDriver(String userid) {

		if (ToolUtil.isEmpty(userid)) {
			return null;
		}

		StringBuffer detailSql = new StringBuffer(DriverSql.DRIVER_DETAIL);

		if (ToolUtil.isNotEmpty(userid)) {
			detailSql.append(" AND a.userId = ?");
		}

		detailSql.append(" ORDER BY b.submitTime DESC");
		String sql = detailSql.toString();

		RespDetailDriverDTO respDetailDriverDto = new RespDetailDriverDTO();

		respDetailDriverDto = Db.querySqlFirst(RespDetailDriverDTO.class, sql, userid);

		return respDetailDriverDto;
	}

	/**
	 * 
	 * @Description: 根据公司名称获取公司所有司机Id
	 * @author haoxiaojun
	 * @date 2016年12月8日 下午12:46:05
	 * @since V 2.5.7
	 */
	@Override
	@Transactional(readOnly = true)
	public List<String> getDriverUserIdsByConditions(List<Integer> organizationIds, String nameOrPhone) {

		StringBuffer userIdsSql = new StringBuffer(DriverSql.GET_USERIDS_BY_COMPANYIDS);

		if (!StringUtils.isBlank(nameOrPhone)) {
			userIdsSql.append(
					" AND (a.`telPhone` LIKE '%" + nameOrPhone + "%' OR b.`trueName` LIKE '%" + nameOrPhone + "%') ");
		}
		userIdsSql.append(" AND b.organizationId in (" + SqlUtil.parse(organizationIds) + ")");

		List<String> results = Db.querySqlBasicTranslationList(String.class, userIdsSql.toString(),
				organizationIds.toArray());
		return results;
	}

	/**
	 * 
	 * @Title: getSpecialUserAuthInfoByDriverId @Description:
	 * 根据司机id查询司机信息 @param 参数说明 @author hufan @return 返回类型 @throws
	 */
	@Override
	@Transactional(readOnly = true)
	public ResDriverBasicInfoDTO getResDriverBasicInfoDTOByDriverId(String driverId) {

		if (ToolUtil.isEmpty(driverId)) {
			return null;
		}
		return Db.querySqlFirst(ResDriverBasicInfoDTO.class, DriverSql.GET_DRIVER_BASIC_INFO_BY_DRIVERID, driverId);
	}
	
	/**
	 * @Description 修改司机的登录状态(1:登录状态  2:退出状态   3:锁定状态)
	 * @author fengshuonan
	 * @date 2017年2月7日 下午12:04:08
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean setDriverLoginStatus(String userId, int status) {
		Specialuserlogin specialuserlogin = Db.queryCriterionFirst(Specialuserlogin.class, Restrictions.eq("suid", userId));
		if(specialuserlogin == null){
			throw new BussinessException(BizExceptionEnum.NO_THIS_USER); 
		}
		if(status == 1 || status == 2 || status ==3){
			specialuserlogin.setUserStatus(status);
			return true;
		}else{
			throw new BussinessException(BizExceptionEnum.ERROR_STATE);
		}
	}

}
